/**
 * 
 */
package org.xserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.xserver.core.util.MapUtil;

/**
 * @author jkonopka
 * 
 */
public final class AppSettings {

	private static final AppSettings INSTANCE = new AppSettings();
	private final Map<String, String> CACHE = new HashMap<String, String>();

	/**
	 * 
	 */
	private AppSettings() {
	}

	/**
	 * @param key Key
	 * @return Value by key
	 */
	public static String getValue(final String key) {
		return getInstance().get(key);
	}

	/**
	 * @param key key
	 * @return Value by the key
	 */
	private String get(final String key) {
		String value = CACHE.get(key);
		if (value == null) {
			reload();
			value = CACHE.get(key);
		}
		return value;
	}

	/**
	 * @return {@link Map} with {@link #CACHE}
	 */
	public static Map<String, String> getValues() {
		if (MapUtil.isEmpty(getInstance().CACHE)) {
			getInstance().reload();
		}
		return getInstance().CACHE;
	}

	/**
	 * 
	 */
	public void reload() {
		CACHE.clear();
		for (final Entry<Object, Object> entry : getProperties().entrySet()) {
			CACHE.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
		}
	}

	/**
	 * @return {@link Properties} from user settings file
	 */
	public synchronized static Properties getProperties() {
		final Properties properties = new Properties();
		InputStream in = null;
		try {
			in = new FileInputStream(new File(Application.getUserSettingsFilename()));
			properties.loadFromXML(in);
		} catch (final Exception e) {
			throw new RuntimeException(Messages.getValue("error.reload.app.settings"));
		} finally {
			IOUtils.closeQuietly(in);
		}
		return properties;
	}

	/**
	 * @return the instance
	 */
	public static AppSettings getInstance() {
		return INSTANCE;
	}

}
